package com.fighthouse.service;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class Upload
 */
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
		//showMeThecontext(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
		//showMeThecontext(request, response);
	}
	private void showMeThecontext(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		
		ServletOutputStream out = null;
		response.setContentType("text/xml");
		out = response.getOutputStream();
		out.println("<response>");
		out.println(getServletContext().getRealPath(""));
		out.println("</response>");
		out.close();
		
	}

	private void doService(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String uploadType = req.getParameter("uploadType");
		String noticiaId = req.getParameter("noticiaId");
		String atletaId = req.getParameter("atletaId");
		String bannerId = req.getParameter("bannerId");
		
		File disk = null;
		FileItem item = null;
		FileItemFactory factory = new DiskFileItemFactory();
		Iterator iter = null;
		List items = null;
		ServletFileUpload upload = new ServletFileUpload();
		upload.setFileItemFactory(factory);
		ServletOutputStream out = null;
		

		try {
			items = upload.parseRequest(req);
			iter = items.iterator();
			res.setContentType("text/xml");
			out = res.getOutputStream();
			out.println("<response>");
			while (iter.hasNext()) {
				item = (FileItem) iter.next();
				if (item.isFormField()) {
					out.println("<field name=\"" + item.getFieldName()
							+ "\" value=\"" + item.getString() + "\" />");
				} else {
					if (uploadType.equals("atleta")) {

						File diretorio = new File(getServletContext().getRealPath("") 
								+ System.getProperty("file.separator")+"assets"
								+ System.getProperty("file.separator")
								+ "atletas"
								+ System.getProperty("file.separator")
								+ atletaId);

						File diretorioThumbs = new File(diretorio.getPath()
								+ System.getProperty("file.separator")
								+ "thumbs");

						MessageDigest md = MessageDigest.getInstance("MD5");
						BigInteger hash = new BigInteger(1, md
								.digest(("" + System.currentTimeMillis())
										.getBytes()));

						String nome = hash.toString(16)
								+ "."
								+ item.getName().substring(
										item.getName().lastIndexOf(".") + 1);

						disk = new File(diretorio.getPath()
								+ System.getProperty("file.separator") + nome);
						File diskThumbs = new File(diretorioThumbs.getPath()
								+ System.getProperty("file.separator") + nome);

						if (disk.exists())
							disk.delete();
						if (diskThumbs.exists())
							diskThumbs.delete();
						if (!diretorioThumbs.isDirectory())
							diretorioThumbs.mkdirs();

						File imgTemp = File.createTempFile(item.getName(), item
								.getName().substring(
										item.getName().lastIndexOf(".") + 1));
						item.write(imgTemp);

						BufferedImage imagem = ImageIO.read(imgTemp);
						BufferedImage imagemThumbs = ImageIO.read(imgTemp);

						int new_w, thumb_w, new_h, thumb_h;
						if (imagem.getWidth() < imagem.getHeight()) {

							thumb_h = 110;
							thumb_w = (imagem.getWidth() * thumb_h)
									/ imagem.getHeight();

							new_h = 480;
							new_w = (imagem.getWidth() * new_h)
									/ imagem.getHeight();

						} else {
							thumb_w = 160;
							thumb_h = (imagem.getHeight() * thumb_w)
									/ imagem.getWidth();

							new_w = 640;
							new_h = (imagem.getHeight() * new_w)
									/ imagem.getWidth();
						}

						BufferedImage new_img = new BufferedImage(new_w, new_h,
								BufferedImage.TYPE_INT_RGB);
						Graphics2D g = new_img.createGraphics();
						g.drawImage(imagem, 0, 0, new_w, new_h, null);

						ImageIO.write(new_img, item.getName().substring(
								item.getName().lastIndexOf(".") + 1)
								.toUpperCase(), disk);

						BufferedImage thumbs = new BufferedImage(thumb_w,
								thumb_h, BufferedImage.TYPE_INT_RGB);
						Graphics2D t = thumbs.createGraphics();
						t.drawImage(imagemThumbs, 0, 0, thumb_w, thumb_h, null);

						ImageIO.write(thumbs, item.getName().substring(
								item.getName().lastIndexOf(".") + 1)
								.toUpperCase(), diskThumbs);

						imgTemp.delete();

						out.println("<file> <name>" + item.getName()
								+ "</name> <newName>" + nome
								+ "</newName></file>");

					}else{
						if (uploadType.equals("noticia")) {

							File diretorio = new File(getServletContext().getRealPath("")+ System.getProperty("file.separator")+"assets"
									+ System.getProperty("file.separator")
									+ "noticias"
									+ System.getProperty("file.separator")
									+ noticiaId);

							File diretorioThumbs = new File(diretorio.getPath()
									+ System.getProperty("file.separator")
									+ "thumbs");

							MessageDigest md = MessageDigest.getInstance("MD5");
							BigInteger hash = new BigInteger(1, md
									.digest(("" + System.currentTimeMillis())
											.getBytes()));

							String nome = hash.toString(16)
									+ "."
									+ item.getName().substring(
											item.getName().lastIndexOf(".") + 1);

							disk = new File(diretorio.getPath()
									+ System.getProperty("file.separator") + nome);
							File diskThumbs = new File(diretorioThumbs.getPath()
									+ System.getProperty("file.separator") + nome);

							if (disk.exists())
								disk.delete();
							if (diskThumbs.exists())
								diskThumbs.delete();
							if (!diretorioThumbs.isDirectory())
								diretorioThumbs.mkdirs();

							File imgTemp = File.createTempFile(item.getName(), item
									.getName().substring(
											item.getName().lastIndexOf(".") + 1));
							item.write(imgTemp);

							BufferedImage imagem = ImageIO.read(imgTemp);
							BufferedImage imagemThumbs = ImageIO.read(imgTemp);

							int new_w, thumb_w, new_h, thumb_h;
							if (imagem.getWidth() < imagem.getHeight()) {

								thumb_h = 110;
								thumb_w = (imagem.getWidth() * thumb_h)
										/ imagem.getHeight();

								new_h = 480;
								new_w = (imagem.getWidth() * new_h)
										/ imagem.getHeight();

							} else {
								thumb_w = 160;
								thumb_h = (imagem.getHeight() * thumb_w)
										/ imagem.getWidth();

								new_w = 640;
								new_h = (imagem.getHeight() * new_w)
										/ imagem.getWidth();
							}

							BufferedImage new_img = new BufferedImage(new_w, new_h,
									BufferedImage.TYPE_INT_RGB);
							Graphics2D g = new_img.createGraphics();
							g.drawImage(imagem, 0, 0, new_w, new_h, null);

							ImageIO.write(new_img, item.getName().substring(
									item.getName().lastIndexOf(".") + 1)
									.toUpperCase(), disk);

							BufferedImage thumbs = new BufferedImage(thumb_w,
									thumb_h, BufferedImage.TYPE_INT_RGB);
							Graphics2D t = thumbs.createGraphics();
							t.drawImage(imagemThumbs, 0, 0, thumb_w, thumb_h, null);

							ImageIO.write(thumbs, item.getName().substring(
									item.getName().lastIndexOf(".") + 1)
									.toUpperCase(), diskThumbs);

							imgTemp.delete();

							out.println("<file> <name>" + item.getName()
									+ "</name> <newName>" + nome
									+ "</newName></file>");

						}else{
							if (uploadType.equals("banner")) {

								File diretorio = new File(getServletContext().getRealPath("")+ System.getProperty("file.separator")+"assets"
										+ System.getProperty("file.separator")
										+ "banners");

								File diretorioThumbs = new File(diretorio.getPath()
										+ System.getProperty("file.separator")
										+ "thumbs");

								MessageDigest md = MessageDigest.getInstance("MD5");
								BigInteger hash = new BigInteger(1, md
										.digest(("" + System.currentTimeMillis())
												.getBytes()));

								String nome = hash.toString(16)
										+ "."
										+ item.getName().substring(
												item.getName().lastIndexOf(".") + 1);

								disk = new File(diretorio.getPath()
										+ System.getProperty("file.separator") + nome);
								File diskThumbs = new File(diretorioThumbs.getPath()
										+ System.getProperty("file.separator") + nome);

								if (disk.exists())
									disk.delete();
								if (diskThumbs.exists())
									diskThumbs.delete();
								if (!diretorioThumbs.isDirectory())
									diretorioThumbs.mkdirs();

								File imgTemp = File.createTempFile(item.getName(), item
										.getName().substring(
												item.getName().lastIndexOf(".") + 1));
								item.write(imgTemp);

								BufferedImage imagem = ImageIO.read(imgTemp);
								BufferedImage imagemThumbs = ImageIO.read(imgTemp);

								int new_w, thumb_w, new_h, thumb_h;
								if (imagem.getWidth() < imagem.getHeight()) {

									thumb_h = 110;
									thumb_w = (imagem.getWidth() * thumb_h)
											/ imagem.getHeight();

								} else {
									thumb_w = 160;
									thumb_h = (imagem.getHeight() * thumb_w)
											/ imagem.getWidth();
								}

								BufferedImage new_img = new BufferedImage(imagem.getWidth(), imagem.getHeight(),
										BufferedImage.TYPE_INT_RGB);
								Graphics2D g = new_img.createGraphics();
								g.drawImage(imagem, 0, 0, imagem.getWidth(), imagem.getHeight(), null);

								ImageIO.write(new_img, item.getName().substring(
										item.getName().lastIndexOf(".") + 1)
										.toUpperCase(), disk);

								BufferedImage thumbs = new BufferedImage(thumb_w,
										thumb_h, BufferedImage.TYPE_INT_RGB);
								Graphics2D t = thumbs.createGraphics();
								t.drawImage(imagemThumbs, 0, 0, thumb_w, thumb_h, null);

								ImageIO.write(thumbs, item.getName().substring(
										item.getName().lastIndexOf(".") + 1)
										.toUpperCase(), diskThumbs);

								imgTemp.delete();

								out.println("<file> <name>" + item.getName()
										+ "</name> <newName>" + nome
										+ "</newName></file>");

							}
						}
					}

				}

			}
			out.println("</response>");
			out.close();
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
